package com.yjz.study.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.yjz.common.extend.showToast
import com.yjz.common.restful.CallBack
import com.yjz.common.restful.HttpBaseResponse
import com.yjz.study.http.ApiFactory
import com.yjz.study.http.api.HomeApi
import com.yjz.study.http.entity.res.HomeModel
import com.yjz.study.http.entity.res.TabCategory

/**
 *作用 : 使用saveState来处理混存首页数据，防止电量不足或者内存不足重建数据问题
 *作者 : yjz
 *时间 : 2025/4/14 10:10
 */
class HomeViewModel(/*用savedState来缓存数据*/val savedState: SavedStateHandle) : ViewModel() {

    // 查询首页tab分类数据
    fun queryCategoryList(): MutableLiveData<List<TabCategory>?> {
        val liveData = MutableLiveData<List<TabCategory>?>()
        // 先从savedState中获取，如果有的话则直接返回
        val memCache = savedState.get<List<TabCategory>?>("categoryTabs")
        if (memCache != null) {
            liveData.postValue(memCache)
            return liveData
        }
        val homeApi = ApiFactory.create(HomeApi::class.java)
        homeApi.category().enqueue(object : CallBack<List<TabCategory>> {
            override fun onSuccess(response: HttpBaseResponse<List<TabCategory>>) {
                val data = response.data
                if (response.successful() && data != null) {
                    liveData.value = data
                    savedState["categoryTabs"] = data
                }
            }

            override fun onFailed(throwable: Throwable) {
                showToast(throwable.message)
            }
        })
        return liveData
    }

    /**
     * 获取指定的分类数据
     */
    fun queryTabCategoryList(categoryId: String?, pageIndex: Int, cacheStrategy: Int): MutableLiveData<HomeModel?> {
        val liveData = MutableLiveData<HomeModel?>()
        // 先从savedState中获取，如果有的话则直接返回
        val memCache = savedState.get<HomeModel?>("categoryList")
        if (memCache != null) {
            liveData.postValue(memCache)
            return liveData
        }

        ApiFactory.create(HomeApi::class.java)
            .subCategories(cacheStrategy, categoryId!!, pageIndex, pageSize = 10).enqueue(object : CallBack<HomeModel> {
                override fun onSuccess(response: HttpBaseResponse<HomeModel>) {
                    val data = response.data
                    if (response.successful() && data != null) {
                        liveData.postValue(data)
                        savedState["categoryList"] = data
                    } else {
                        liveData.postValue(null)
                    }
                }

                override fun onFailed(throwable: Throwable) {
                    liveData.postValue(null)
                }
            })
        return liveData;
    }

}